// Gravity - Version 1.3

// This script applies gravitational force to the layer in layer popup 1.
// The velocity of the layer at the start of the work area
// will be used as the initial velocity.

//      LAYER                                               PROPERTY                     CHANNEL
//      ------                                              ----------                     --------
// 1: Layer affected by gravity                  doesn't matter               doesn't matter
// 2: doesn't matter                                   doesn't matter               doesn't matter

if (time() == start_time) {
	vel = tmap (time() + step_time, value(pop_layer(1), position)) -
           value(pop_layer(1), position);
	damping = 0.95;							    // Damping force (0 = infinite friction, 1 = none)
	grav = 0.9;								         // magnitude of gravity force
	grav_dir = {0,1,0};						// direction of gravity
	accel = grav * grav_dir;	  // gravity vector

	new_pos = value(pop_layer(1), position);
} else {

	vel = vel*damping + accel;						// Add discrete acceleration to velocity
	new_pos = new_pos + vel;		         // Add discrete velocity to position
	
	// Check new position against borders of comp and bounce back
	if (new_pos[X] < 0) {
		new_pos[X] = 0;
		vel = {-vel[X], vel[Y]};
	}
	if (new_pos[Y] < 0) {
		new_pos[Y] = 0;
		vel = {vel[X], -vel[Y]};
	}
	if (new_pos[X] > comp_size[X]) {
		new_pos[X] = comp_size[X];
		vel = {-vel[X], vel[Y]};
	}
	if (new_pos[Y] > comp_size[Y]) {
		new_pos[Y] = comp_size[Y];
		vel = {vel[X], -vel[Y]};
	}	
}
value(pop_layer(1), position) = new_pos;
